<?php
namespace App\Models\Scope;

use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

use App\Models\SyUser;
use App\Models\Area;

/**
 * 公司限制
 * @author litc
 */
class SiteScope implements Scope {
    


    public function apply(Builder $builder, Model $model)
    {
        $table = $model->getTable();
        $user = null;
        if(!$model instanceof SyUser){
            $user = auth()->user();
        }

        if(!$user) {
            return $builder;
        }

        $cid = $user->Co_ID;
        if($cid){
           $builder->where($table.'.'.$model->getCompanyField(), '=', $cid); 
        }
        
        $sid = $user->scope;
        if(!$sid) {
            return $builder;
        }
        $aids = Area::whereDescendantOrSelf($sid)->get()->pluck('AreaId')->toArray();
        $builder->whereIn($table.'.'.$model->getSiteField(), $aids);
       // $builder -> where($table.'.'.$model->getSiteField(), '=', $sid);
        return $builder;
    }
    
}
